package com.myblog.service.impl;

import com.myblog.constant.RedisHashKey;
import com.myblog.constant.RedisKey;
import com.myblog.model.Visitor;
import com.myblog.redis.RedisService;
import com.myblog.service.StatisticsService;
import com.myblog.service.impl.redis.HashRedisServiceImpl;
import com.myblog.utils.DataMap;
import com.myblog.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private HashRedisServiceImpl hashRedisService;


    @Override
    public DataMap getStatisticsInfo() {
        //从redis中获取总访客量信息
        Object totalVisitorNum =  redisService.getHash(RedisKey.VISITOR, RedisHashKey.TOTAL_VISITOR);
        //判断数据是否为空，如果为空调用函数进行处理
        Visitor totalVisitor = redisService.visitorMsgIfExist(totalVisitorNum, RedisHashKey.TOTAL_VISITOR);
        //从redis中获取user数量信息
        Object allUser =  redisService.getHash(RedisKey.STATISTICS,RedisHashKey.ALL_USER);
        Integer NumOfUser = redisService.numOfAllUserIfExist(allUser);
        //从redis中获取article数量信息
        Object articleNum = redisService.getHash(RedisKey.STATISTICS,RedisHashKey.ARTICLE_NUM);
        Integer NumOfArticle = redisService.numOfAllArticleIfExist(articleNum);
        //从redis中获取文章的总点赞量
        Object articleLikeNum = redisService.getHash(RedisKey.STATISTICS,RedisHashKey.ARTICLE_LIKE_NUM);
        int NumOfArticleLike;
        if (articleLikeNum != null){
            NumOfArticleLike = Integer.parseInt(articleLikeNum.toString());
        }
        else {
            NumOfArticleLike = 0;
        }
        //从redis中获取昨日访客量，昨日访客量由任务定时器实现config/ScheduleTask
        Object yesterdayVisitorMsg =redisService.getHash(RedisKey.VISITOR,RedisHashKey.YESTERDAY_TOTAL_VISITOR);
        if(yesterdayVisitorMsg == null){
            hashRedisService.put(RedisKey.VISITOR,RedisHashKey.YESTERDAY_TOTAL_VISITOR,0);
        }
        Integer yesterdayVisitor = Integer.valueOf(yesterdayVisitorMsg.toString());

        HashMap<String,Object> result = new HashMap<>();
        result.put("allVisitor",totalVisitor.getVisitorNum());
        result.put("allUser",NumOfUser);
        result.put("articleNum",NumOfArticle);
        result.put("yesterdayVisitor",yesterdayVisitor);
        result.put("articleThumbsUpNum",NumOfArticleLike);

        return DataMap.success().setData(result);
    }
}
